<template>
	<div class="app-container">
		<!-- 顶部统计卡片 -->
		<el-row :gutter="20">
			<el-col :span="6">
				<el-card>
					<div class="stat-card">
						<h3>今日工单总数</h3>
						<div class="number">{{ statisticsData.totalCount || 0 }}</div>
						<div
							class="trend"
							:class="getTrendClass(statisticsData.totalGrowthRate)"
						>
							<span>{{ statisticsData.totalGrowthRate || "0%" }}</span>
							<el-icon>
								<component :is="getTrendIcon(statisticsData.totalGrowthRate)" />
							</el-icon>
						</div>
					</div>
				</el-card>
			</el-col>

			<el-col :span="6">
				<el-card>
					<div class="stat-card">
						<h3>待处理工单</h3>
						<div class="number">{{ statisticsData.pendingCount || 0 }}</div>
						<div
							class="trend"
							:class="getTrendClass(statisticsData.pendingGrowthRate)"
						>
							<span>{{ statisticsData.pendingGrowthRate || "0%" }}</span>
							<el-icon>
								<component
									:is="getTrendIcon(statisticsData.pendingGrowthRate)"
								/>
							</el-icon>
						</div>
					</div>
				</el-card>
			</el-col>

			<el-col :span="6">
				<el-card>
					<div class="stat-card">
						<h3>处理中工单</h3>
						<div class="number">{{ statisticsData.processingCount || 0 }}</div>
						<div
							class="trend"
							:class="getTrendClass(statisticsData.processingGrowthRate)"
						>
							<span>{{ statisticsData.processingGrowthRate || "0%" }}</span>
							<el-icon>
								<component
									:is="getTrendIcon(statisticsData.processingGrowthRate)"
								/>
							</el-icon>
						</div>
					</div>
				</el-card>
			</el-col>

			<el-col :span="6">
				<el-card>
					<div class="stat-card">
						<h3>已完成工单</h3>
						<div class="number">{{ statisticsData.completedCount || 0 }}</div>
						<div
							class="trend"
							:class="getTrendClass(statisticsData.completedGrowthRate)"
						>
							<span>{{ statisticsData.completedGrowthRate || "0%" }}</span>
							<el-icon>
								<component
									:is="getTrendIcon(statisticsData.completedGrowthRate)"
								/>
							</el-icon>
						</div>
					</div>
				</el-card>
			</el-col>
		</el-row>

		<el-row :gutter="20" class="mt-20">
			<!-- 工单日历 -->
			<el-col :span="8">
				<el-card>
					<el-calendar v-model="calendarValue">
						<template #date-cell="{ data, date }">
							<!-- 显示日期数字 -->
							<div
								style="height: 100%"
								class="date-number"
								@click="calendarOnClick(data.day)"
							>
								{{ data.day.split("-")[2] }}
							</div>
						</template>
					</el-calendar>
				</el-card>
			</el-col>

			<!-- 统计图表区域 -->
			<el-col :span="16">
				<el-card style="height: 100%">
					<div style="display: flex; justify-content: end">
						<el-radio-group v-model="activeChart" @change="handleChartChange">
							<el-radio-button value="type">类型分布</el-radio-button>
							<el-radio-button value="trend">趋势分析</el-radio-button>
							<el-radio-button value="department">部门完成率</el-radio-button>
						</el-radio-group>
					</div>
					<ECharts class="mt-2" :option="chartOption" style="height: 500px" />
				</el-card>
			</el-col>
		</el-row>

		<el-row class="mt-20">
			<el-col :span="24">
				<el-card>
					<template #header>
						<div class="table-header">
							<span>工单列表</span>
							<div class="search-bar">
								<el-input
									v-model="queryParams.workOrderNumber"
									placeholder="搜索工单编号"
									clearable
									style="width: 200px; margin-right: 10px"
									@keyup.enter="handleQuery"
								/>
								<el-select
									v-model="queryParams.workOrderStatus"
									placeholder="状态筛选"
									clearable
									@change="handleQuery"
								>
									<el-option
										v-for="item in statusOptions"
										:key="item"
										:label="item"
										:value="item"
									/>
								</el-select>
							</div>
						</div>
						<el-button type="primary" icon="Plus" @click="handleAdd">
							新增工单
						</el-button>
					</template>

					<el-table
						:data="workOrderList"
						border
						v-loading="loading"
						@selection-change="handleSelectionChange"
					>
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column
							prop="workOrderId"
							label="工单编号"
							width="150"
							align="center"
						/>
						<el-table-column
							prop="workOrderType"
							label="工单类型"
							width="120"
							align="center"
						/>
						<el-table-column
							prop="workOrderDescription"
							label="工单描述"
							align="center"
						/>
						<el-table-column
							prop="creationTime"
							label="创建时间"
							width="180"
							align="center"
						/>
						<el-table-column
							prop="workOrderStatus"
							label="工单状态"
							width="120"
							align="center"
						>
							<template #default="{ row }">
								<el-tag :type="getStatusTagType(row.workOrderStatus)">
									{{ row.workOrderStatus }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="240" align="center">
							<template #default="{ row }">
								<el-button size="small" @click="handleView(row)"
									>查看</el-button
								>
								<el-button size="small" type="warning" @click="handleEdit(row)"
									>编辑</el-button
								>
								<el-button
									size="small"
									type="primary"
									@click="handleProcess(row)"
									v-if="row.workOrderStatus === '未处理'"
								>
									处理
								</el-button>
								<el-button
									size="small"
									type="primary"
									@click="finishProcess(row)"
									v-if="row.workOrderStatus === '处理中'"
								>
									完成
								</el-button>
							</template>
						</el-table-column>
					</el-table>

					<el-pagination
						class="mt-2"
						background
						layout="total, sizes, prev, pager, next, jumper"
						:total="total"
						v-model:page-size="queryParams.pageSize"
						v-model:current-page="queryParams.pageNum"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</el-card>
			</el-col>
		</el-row>

		<!-- 工单详情对话框 -->
		<el-dialog v-model="detailDialogVisible" title="工单详情" width="50%">
			<div v-if="currentWorkOrder" class="work-order-detail">
				<el-descriptions :column="1" border>
					<el-descriptions-item label="工单编号">{{
						currentWorkOrder.workOrderId
					}}</el-descriptions-item>
					<el-descriptions-item label="工单类型">{{
						currentWorkOrder.workOrderType
					}}</el-descriptions-item>
					<el-descriptions-item label="工单描述">{{
						currentWorkOrder.workOrderDescription
					}}</el-descriptions-item>
					<el-descriptions-item label="创建时间">{{
						currentWorkOrder.creationTime
					}}</el-descriptions-item>
					<el-descriptions-item label="工单状态">
						<el-tag :type="getStatusTagType(currentWorkOrder.workOrderStatus)">
							{{ currentWorkOrder.workOrderStatus }}
						</el-tag>
					</el-descriptions-item>
					<!-- <el-descriptions-item label="负责人">{{
						currentWorkOrder.responsiblePersonId
					}}</el-descriptions-item> -->
					<el-descriptions-item label="负责人">
						{{ getName(userOptions, currentWorkOrder.id, "id", "name") }}
					</el-descriptions-item>
				</el-descriptions>
			</div>
			<template #footer>
				<el-button @click="detailDialogVisible = false">关闭</el-button>
				<el-button
					type="primary"
					@click="handleProcess(currentWorkOrder)"
					v-if="currentWorkOrder?.workOrderStatus === '待处理'"
				>
					处理工单
				</el-button>
			</template>
		</el-dialog>

		<!-- 处理工单对话框 -->
		<el-dialog v-model="processDialogVisible" title="处理工单" width="50%">
			<el-form :model="processForm" label-width="100px">
				<el-form-item label="工单编号">
					<el-input v-model="currentWorkOrder.workOrderId" disabled />
				</el-form-item>
				<el-form-item label="工单类型">
					<el-input v-model="currentWorkOrder.workOrderType" disabled />
				</el-form-item>
				<el-form-item label="处理说明" prop="remarks" required>
					<el-input
						v-model="processForm.remarks"
						type="textarea"
						:rows="4"
						placeholder="请输入处理说明"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="processDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitProcess">确认处理</el-button>
			</template>
		</el-dialog>

		<!-- 添加或修改工单统计对话框 -->
		<el-dialog :title="title" v-model="open" width="500px" append-to-body>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="工单编号" prop="workOrderId">
					<el-input
						v-model="form.workOrderId"
						placeholder="请输入工单编号"
						:disabled="form.id !== undefined"
					/>
				</el-form-item>
				<el-form-item label="工单类型" prop="workOrderType">
					<el-select v-model="form.workOrderType" placeholder="请选择工单类型">
						<el-option label="设备维修工单" value="设备维修工单" />
						<el-option label="巡检工单" value="巡检工单" />
						<el-option label="水质检测工单" value="水质检测工单" />
						<el-option label="管道维护工单" value="管道维护工单" />
						<el-option label="系统维护工单" value="系统维护工单" />
					</el-select>
				</el-form-item>
				<el-form-item label="工单描述" prop="workOrderDescription">
					<el-input
						v-model="form.workOrderDescription"
						type="textarea"
						placeholder="请输入工单描述"
					/>
				</el-form-item>
				<el-form-item label="创建时间" prop="creationTime">
					<el-date-picker
						clearable
						v-model="form.creationTime"
						type="datetime"
						value-format="yyyy-MM-dd HH:mm:ss"
						placeholder="请选择创建时间"
					/>
				</el-form-item>
				<el-form-item label="预计完成时间" prop="expectedCompletionTime">
					<el-date-picker
						clearable
						v-model="form.expectedCompletionTime"
						type="datetime"
						value-format="yyyy-MM-dd HH:mm:ss"
						placeholder="请选择预计完成时间"
					/>
				</el-form-item>
				<el-form-item label="实际完成时间" prop="actualCompletionTime">
					<el-date-picker
						clearable
						v-model="form.actualCompletionTime"
						type="datetime"
						value-format="yyyy-MM-dd HH:mm:ss"
						placeholder="请选择实际完成时间"
					/>
				</el-form-item>
				<el-form-item label="工单状态" prop="workOrderStatus">
					<el-select
						v-model="form.workOrderStatus"
						placeholder="请选择工单状态"
					>
						<el-option label="未处理" value="未处理" />
						<el-option label="处理中" value="处理中" />
						<el-option label="已完成" value="已完成" />
					</el-select>
				</el-form-item>
				<el-form-item label="紧急程度(1-5)" prop="urgencyLevel">
					<el-input
						v-model="form.urgencyLevel"
						type="number"
						min="1"
						max="5"
						placeholder="1-5之间的数字"
					/>
				</el-form-item>
				<!-- <el-form-item label="负责人ID" prop="responsiblePersonId">
					<el-input
						v-model="form.responsiblePersonId"
						type="number"
						placeholder="请输入负责人ID"
					/>
				</el-form-item> -->
				<el-form-item label="值班人员" prop="responsiblePersonId">
					<el-select
						v-model="form.responsiblePersonId"
						placeholder="请选择负责人"
						style="width: 100%"
					>
						<el-option
							v-for="item in userOptions"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="分配时间" prop="assignmentTime">
					<el-date-picker
						clearable
						v-model="form.assignmentTime"
						type="datetime"
						value-format="yyyy-MM-dd HH:mm:ss"
						placeholder="请选择分配时间"
					/>
				</el-form-item>
				<el-form-item label="处理时长(小时)" prop="processingTime">
					<el-input
						v-model="form.processingTime"
						type="number"
						step="0.01"
						min="0"
						placeholder="请输入处理时长"
					/>
				</el-form-item>
				<el-form-item label="备注信息" prop="remark">
					<el-input
						v-model="form.remark"
						type="textarea"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
				<el-form-item label="附件路径" prop="attachmentPath">
					<el-input
						v-model="form.attachmentPath"
						placeholder="请输入附件路径"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, computed } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import { ArrowUp, ArrowDown } from "@element-plus/icons-vue";
	import ECharts from "@/components/ECharts";
	import {
		getStatusList,
		listWorkOrderStatistics,
		getWorkOrderStatistics,
		handleWorkOrder,
		countWorkOrderStatistics,
		getTypeDistribution,
		getTrendAnalysis,
		getDepartmentCompletionRate,
		finishWorkOrder,
		addOperationWorkOrderStatistics,
		updateOperationWorkOrderStatistics,
		getUserList,
	} from "@/api/prod_operate/synthesis/worder";
	// 新增变量
	const userOptions = ref([]);
	const open = ref(false);
	const title = ref("");
	const formRef = ref(null);
	const form = reactive({
		id: undefined,
		workOrderId: "",
		workOrderType: "",
		workOrderDescription: "",
		creationTime: "",
		expectedCompletionTime: "",
		actualCompletionTime: "",
		workOrderStatus: "",
		urgencyLevel: 1,
		responsiblePersonId: "",
		assignmentTime: "",
		processingTime: null,
		remark: "",
		attachmentPath: "",
	});
	const rules = reactive({
		workOrderId: [
			{ required: true, message: "请输入工单编号", trigger: "blur" },
			{ max: 50, message: "工单编号长度不能超过50个字符", trigger: "blur" },
		],
		workOrderType: [
			{ required: true, message: "请选择工单类型", trigger: "change" },
		],
		workOrderDescription: [
			{ required: true, message: "请输入工单描述", trigger: "blur" },
		],
		creationTime: [
			{ required: true, message: "请选择创建时间", trigger: "change" },
		],
		workOrderStatus: [
			{ required: true, message: "请选择工单状态", trigger: "change" },
		],
		responsiblePersonId: [
			{ required: true, message: "请输入负责人ID", trigger: "blur" },
			{ type: "number", message: "负责人ID必须为数字", trigger: "blur" },
		],
	});
	// 获取用户列表
	const fetchUserList = async () => {
		try {
			const res = await getUserList();
			userOptions.value = res.data || [];
		} catch (error) {
			console.error("获取用户列表失败:", error);
			ElMessage.error("获取用户列表失败");
		}
	};
	const getUserName = (userId) => {
		const userItem = userOptions.value.find((item) => item.id === userId);
		return userItem ? userItem.name : "-";
	};
	const getName = (list, value, keyField, nameField) => {
		const item = list.find((item) => item[keyField] === value);
		return item ? item[nameField] : "-";
	};
	// 在原有方法基础上添加
	// 打开新增对话框
	const handleAdd = () => {
		resetForm();
		title.value = "新增工单";
		open.value = true;
		// 自动生成工单编号（示例）
		form.workOrderId = `WO-${new Date().getFullYear()}-${Math.floor(
			Math.random() * 1000
		)
			.toString()
			.padStart(3, "0")}`;
		// 默认创建时间为当前时间
		form.creationTime = new Date().toISOString().slice(0, 19).replace("T", " ");
		form.workOrderStatus = "未处理";
	};

	// 打开编辑对话框
	const handleEdit = async (row) => {
		resetForm();
		title.value = "修改工单";
		// 获取工单详情
		try {
			const res = await getWorkOrderStatistics(row.id);
			form.id = res.data.id;
			form.workOrderId = res.data.workOrderId;
			form.workOrderType = res.data.workOrderType;
			form.workOrderDescription = res.data.workOrderDescription;
			form.creationTime = res.data.creationTime;
			form.expectedCompletionTime = res.data.expectedCompletionTime;
			form.actualCompletionTime = res.data.actualCompletionTime;
			form.workOrderStatus = res.data.workOrderStatus;
			form.urgencyLevel = res.data.urgencyLevel;
			form.responsiblePersonId = res.data.responsiblePersonId;
			form.assignmentTime = res.data.assignmentTime;
			form.processingTime = res.data.processingTime;
			form.remark = res.data.remark;
			form.attachmentPath = res.data.attachmentPath;
			open.value = true;
		} catch (error) {
			console.error("获取工单详情失败:", error);
			ElMessage.error("获取工单详情失败");
		}
	};

	// 重置表单
	const resetForm = () => {
		formRef.value?.resetFields();
		Object.assign(form, {
			id: undefined,
			workOrderId: "",
			workOrderType: "",
			workOrderDescription: "",
			creationTime: "",
			expectedCompletionTime: "",
			actualCompletionTime: "",
			workOrderStatus: "",
			urgencyLevel: 1,
			responsiblePersonId: "",
			assignmentTime: "",
			processingTime: null,
			remark: "",
			attachmentPath: "",
		});
	};

	// 提交表单
	const submitForm = async () => {
		try {
			await formRef.value.validate();
			// 处理日期格式（转为ISO格式）
			const formData = { ...form };
			if (formData.creationTime)
				formData.creationTime = new Date(formData.creationTime).toISOString();
			if (formData.expectedCompletionTime)
				formData.expectedCompletionTime = new Date(
					formData.expectedCompletionTime
				).toISOString();
			if (formData.actualCompletionTime)
				formData.actualCompletionTime = new Date(
					formData.actualCompletionTime
				).toISOString();
			if (formData.assignmentTime)
				formData.assignmentTime = new Date(
					formData.assignmentTime
				).toISOString();

			if (formData.id) {
				// 修改操作
				await updateOperationWorkOrderStatistics(formData);
				ElMessage.success("修改成功");
			} else {
				// 新增操作
				await addOperationWorkOrderStatistics(formData);
				ElMessage.success("新增成功");
			}
			open.value = false;
			fetchWorkOrderList();
			fetchStatisticsData();
		} catch (error) {
			if (error.name === "ValidationError") return;
			console.error("操作失败:", error);
			ElMessage.error(form.id ? "修改失败" : "新增失败");
		}
	};

	// 取消操作
	const cancel = () => {
		open.value = false;
		resetForm();
	};
	// 查询参数
	const queryParams = reactive({
		pageNum: 1,
		pageSize: 10,
		workOrderNumber: "",
		workOrderStatus: "",
	});

	// 表单数据
	const processForm = reactive({
		id: null,
		remarks: "",
	});

	// 对话框控制
	const detailDialogVisible = ref(false);
	const processDialogVisible = ref(false);

	// 当前操作的工单
	const currentWorkOrder = ref(null);

	// 下拉选项数据
	const statusOptions = ref([]);

	// 表格数据
	const workOrderList = ref([]);
	const total = ref(0);
	const loading = ref(false);
	const selectedRows = ref([]);

	// 统计卡片数据
	const statisticsData = reactive({
		totalCount: 0,
		totalGrowthRate: "0%",
		pendingCount: 0,
		pendingGrowthRate: "0%",
		processingCount: 0,
		processingGrowthRate: "0%",
		completedCount: 0,
		completedGrowthRate: "0%",
	});

	// 图表控制
	const activeChart = ref("type");
	const chartOption = ref({});

	// 日历值
	const calendarValue = ref(new Date());
	// 处理日历日期变化
	const calendarOnClick = (date) => {
		console.log("点击的日期:", date);
		calendarValue.value = date;
		fetchChartData();
	};

	// 初始化加载数据
	onMounted(() => {
		fetchStatusOptions();
		fetchStatisticsData();
		fetchWorkOrderList();
		fetchChartData();
		fetchUserList();
	});

	// 获取状态下拉选项
	const fetchStatusOptions = async () => {
		try {
			const res = await getStatusList();
			statusOptions.value = res.data || [];
		} catch (error) {
			console.error("获取状态下拉选项失败:", error);
			ElMessage.error("获取状态下拉选项失败");
		}
	};

	// 获取统计卡片数据
	const fetchStatisticsData = async () => {
		try {
			const res = await countWorkOrderStatistics();
			Object.assign(statisticsData, res.data || {});
		} catch (error) {
			console.error("获取统计卡片数据失败:", error);
			ElMessage.error("获取统计卡片数据失败");
		}
	};

	// 获取工单列表
	const fetchWorkOrderList = async () => {
		try {
			loading.value = true;
			const res = await listWorkOrderStatistics(queryParams);
			workOrderList.value = res.rows || [];
			total.value = res.total || 0;
		} catch (error) {
			console.error("获取工单列表失败:", error);
			ElMessage.error("获取工单列表失败");
		} finally {
			loading.value = false;
		}
	};
	// 格式化日期为 YYYY-MM 或 YYYY-MM-DD（根据需要选择）
	const formatDate = (date) => {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需 +1
		const day = String(date.getDate()).padStart(2, "0");
		// 根据图表需求返回格式：趋势分析可能需要月份（YYYY-MM），具体日期用 YYYY-MM-DD
		return `${year}-${month}-${day}`; // 若需要具体日期则返回 `${year}-${month}-${day}`
	};
	// 获取图表数据
	const fetchChartData = async () => {
		var date;
		if (calendarValue.value instanceof Date) {
			date = formatDate(calendarValue.value);
		} else {
			date = calendarValue.value;
		}
		try {
			let res;
			switch (activeChart.value) {
				case "type":
					res = await getTypeDistribution({ date });
					chartOption.value = generateTypeDistributionOption(res.data);
					break;
				case "trend":
					res = await getTrendAnalysis({ date });
					chartOption.value = generateTrendAnalysisOption(res.data);
					break;
				case "department":
					res = await getDepartmentCompletionRate({ date });
					chartOption.value = generateDepartmentCompletionOption(res.data);
					break;
			}
		} catch (error) {
			console.error("获取图表数据失败:", error);
			ElMessage.error("获取图表数据失败");
		}
	};

	// 生成类型分布图表配置
	const generateTypeDistributionOption = (data) => {
		return {
			tooltip: {
				trigger: "item",
			},
			legend: {
				orient: "vertical",
				right: 10,
				top: "center",
			},
			series: [
				{
					name: "工单类型分布",
					type: "pie",
					radius: ["40%", "70%"],
					avoidLabelOverlap: false,
					itemStyle: {
						borderRadius: 10,
						borderColor: "#fff",
						borderWidth: 2,
					},
					label: {
						show: false,
						position: "center",
					},
					emphasis: {
						label: {
							show: true,
							fontSize: "18",
							fontWeight: "bold",
						},
					},
					labelLine: {
						show: false,
					},
					data: data.map((item) => ({
						value: item.value,
						name: item.name,
					})),
				},
			],
		};
	};

	// 生成趋势分析图表配置
	const generateTrendAnalysisOption = (data) => {
		return {
			tooltip: {
				trigger: "axis",
				axisPointer: {
					type: "cross",
				},
			},
			legend: {
				data: data.series.map((item) => item.name),
			},
			xAxis: {
				type: "category",
				boundaryGap: false,
				data: data.dateList,
			},
			yAxis: {
				type: "value",
				name: "工单数量",
			},
			series: data.series.map((item) => ({
				name: item.name,
				type: "line",
				data: item.data,
				smooth: true,
				symbol: "circle",
				symbolSize: 8,
				lineStyle: {
					width: 3,
				},
			})),
		};
	};

	// 生成部门完成率图表配置
	const generateDepartmentCompletionOption = (data) => {
		return {
			tooltip: {
				trigger: "axis",
				axisPointer: {
					type: "shadow",
				},
			},
			grid: {
				left: "3%",
				right: "4%",
				bottom: "3%",
				containLabel: true,
			},
			xAxis: {
				type: "value",
			},
			yAxis: {
				type: "category",
				data: data.indicatorNames,
			},
			series: [
				{
					name: "完成率",
					type: "bar",
					data: data.values,
					itemStyle: {
						color: "#409EFF",
					},
					label: {
						show: true,
						position: "right",
					},
				},
			],
		};
	};

	// 获取趋势图标和样式
	const getTrendIcon = (rate) => {
		if (!rate) return ArrowUp;
		return rate.includes("-") ? ArrowDown : ArrowUp;
	};

	const getTrendClass = (rate) => {
		if (!rate) return "up";
		return rate.includes("-") ? "down" : "up";
	};

	// 获取状态标签类型
	const getStatusTagType = (status) => {
		const map = {
			待处理: "danger",
			处理中: "warning",
			已完成: "success",
		};
		return map[status] || "info";
	};

	// 查询按钮
	const handleQuery = () => {
		queryParams.pageNum = 1;
		fetchWorkOrderList();
	};

	// 分页大小变化
	const handleSizeChange = (size) => {
		queryParams.pageSize = size;
		fetchWorkOrderList();
	};

	// 当前页码变化
	const handleCurrentChange = (page) => {
		queryParams.pageNum = page;
		fetchWorkOrderList();
	};

	// 表格选择变化
	const handleSelectionChange = (selection) => {
		selectedRows.value = selection;
	};

	// 图表切换
	const handleChartChange = () => {
		fetchChartData();
	};

	// 查看工单详情
	const handleView = async (row) => {
		try {
			const res = await getWorkOrderStatistics(row.id);
			currentWorkOrder.value = res.data;
			detailDialogVisible.value = true;
		} catch (error) {
			console.error("获取工单详情失败:", error);
			ElMessage.error("获取工单详情失败");
		}
	};

	// 处理工单
	const handleProcess = (row) => {
		currentWorkOrder.value = row;
		processForm.id = row.id;
		processForm.remarks = "";

		// 如果是从详情对话框点击的处理按钮，先关闭详情对话框
		detailDialogVisible.value = false;
		processDialogVisible.value = true;
	};
	const finishProcess = async (row) => {
		await finishWorkOrder(row.id);
	};
	// 提交处理
	const submitProcess = async () => {
		try {
			if (!processForm.remarks) {
				ElMessage.error("请输入处理说明");
				return;
			}

			await handleWorkOrder(processForm);
			ElMessage.success("处理成功");
			processDialogVisible.value = false;
			fetchWorkOrderList();
			fetchStatisticsData();
		} catch (error) {
			console.error("处理工单失败:", error);
			ElMessage.error("处理工单失败");
		}
	};
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.mt-20 {
		margin-top: 20px;
	}

	.stat-card {
		text-align: center;
	}

	.stat-card h3 {
		margin: 0 0 10px 0;
		font-size: 16px;
		color: #666;
	}

	.stat-card .number {
		font-size: 28px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.stat-card .trend {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
	}

	.trend.up {
		color: #67c23a;
	}

	.trend.down {
		color: #f56c6c;
	}

	.table-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search-bar {
		display: flex;
	}

	.work-order-detail {
		padding: 10px;
	}
</style>
